package com.rpoonolly.simplegame.mapio.jsoncoders;

import java.io.IOException;

import org.apache.commons.lang3.ArrayUtils;
import org.json.simple.JSONObject;

import com.rpoonolly.simplegame.Config;
import com.rpoonolly.simplegame.textures.TextureFileDescriptor;

public class TextureFileDescriptorJSONCoder extends JSONCoder<TextureFileDescriptor> {
	private static TextureFileDescriptorJSONCoder singletonInstance;

	private TextureFileDescriptorJSONCoder() {}

	public static TextureFileDescriptorJSONCoder getInstance() {
		if (singletonInstance == null) {
			singletonInstance = new TextureFileDescriptorJSONCoder();
		}

		return singletonInstance;
	}

	@SuppressWarnings("unchecked")
	@Override
	public JSONObject encode(TextureFileDescriptor obj) throws IOException {
		JSONObject jsonTextFile = new JSONObject();
		jsonTextFile.put("fileId", ArrayUtils.indexOf(Config.TEXTURE_FILE_LIST, obj));
		return jsonTextFile;
	}

	@Override
	public TextureFileDescriptor decode(JSONObject code) throws IOException {
		int index = (Integer) code.get("fileId");
		if (index < 0 || index >= Config.TEXTURE_FILE_LIST.length)
			throw new NumberFormatException();
		
		return Config.TEXTURE_FILE_LIST[index];
	}
}
